/*
 * Project Name: jmax
 * File Name: WechatServiceImpl.java
 * Copyright: Copyright(C) 1985-2016 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.wx.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xdtech.wx.message.resp.Article;
import com.xdtech.wx.message.resp.NewsMessageResp;
import com.xdtech.wx.message.resp.TextMessageResp;
import com.xdtech.wx.model.WeixinAccount;
import com.xdtech.wx.model.WeixinReceiveMsg;
import com.xdtech.wx.model.WeixinResponse;
import com.xdtech.wx.service.WechatService;
import com.xdtech.wx.service.WeixinAccountService;
import com.xdtech.wx.service.WeixinReceiveMsgService;
import com.xdtech.wx.service.WeixinResponseService;
import com.xdtech.wx.util.MessageUtil;

/**
 * TODO 一句话功能简述，请确保和下面的block tags之间保留一行空行
 * <p>
 * TODO 功能详细描述，若不需要请连同上面的p标签一起删除
 * 
 * @author <a href="max.zheng@zkteco.com">郑志雄</>
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2016-3-11 下午2:38:20
 */
@Service
public class WechatServiceImpl implements WechatService
{
	private Log log = LogFactory.getLog(WechatServiceImpl.class);
	@Autowired
	private WeixinReceiveMsgService weixinReceiveMsgService;
	@Autowired
	private WeixinResponseService weixinResponseService;
	@Autowired
	private WeixinAccountService weixinAccountService;
	/* (非 Javadoc)
	 * handleTextMsg
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param fromUserName
	 * @param toUserName
	 * @param createTime
	 * @param msgType
	 * @param content
	 * @param msgId
	 * @return
	 * @see com.xdtech.wx.service.WechatService#handleTextMsg(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public String handleTextMsg(String fromUserName, String toUserName, String createTime, String msgType, String content, String msgId,TextMessageResp textMessage)
	{
		WeixinReceiveMsg receiveMsg = new WeixinReceiveMsg(fromUserName,toUserName,createTime,msgType,content,msgId);
		weixinReceiveMsgService.save(receiveMsg);
		WeixinAccount weixinAccount = weixinAccountService.findByAccountId(toUserName);
		WeixinResponse firstResponse = findByKey(weixinAccount.getOriginalId(),content);
		String respMessage = null;
		if (null != firstResponse)
		{
			String resMsgType = firstResponse.getMsgType();
			if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(resMsgType)) {
				//根据返回消息key，获取对应的文本消息返回给微信客户端
//				TextTemplate textTemplate = textTemplateDao.getTextTemplate(sys_accountId, autoResponse.getTemplateName());
				textMessage.setContent(firstResponse.getResContent());
				respMessage = MessageUtil.textMessageToXml(textMessage);
			} else if (MessageUtil.RESP_MESSAGE_TYPE_NEWS.equals(resMsgType)) {
//				List<NewsItem> newsList = this.newsItemService.findByProperty(NewsItem.class,"newsTemplate.id", autoResponse.getResContent());
//				NewsTemplate newsTemplate = newsTemplateService.getEntity(NewsTemplate.class, autoResponse.getResContent());
//				List<Article> articleList = new ArrayList<Article>();
//				for (NewsItem news : newsList) {
//					Article article = new Article();
//					article.setTitle(news.getTitle());
//					article.setPicUrl(bundler.getString("domain") + "/"+ news.getImagePath());
//					String url = "";
//					if (oConvertUtils.isEmpty(news.getUrl())) {
//						url = bundler.getString("domain")+ "/newsItemController.do?newscontent&id="+ news.getId();
//					} else {
//						url = news.getUrl();
//					}
//					article.setUrl(url);
//					article.setDescription(news.getDescription());
//					articleList.add(article);
//				}
//				NewsMessageResp newsResp = new NewsMessageResp();
//				newsResp.setCreateTime(new Date().getTime());
//				newsResp.setFromUserName(toUserName);
//				newsResp.setToUserName(fromUserName);
//				newsResp.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//				newsResp.setArticleCount(newsList.size());
//				newsResp.setArticles(articleList);
//				respMessage = MessageUtil.newsMessageToXml(newsResp);
			}
		}
		else
		{
			// Step.2  通过微信扩展接口（支持二次开发，例如：翻译，天气）
//			log.info("------------微信客户端发送请求--------------Step.2  通过微信扩展接口（支持二次开发，例如：翻译，天气）---");
//			List<WeixinExpandconfigEntity> weixinExpandconfigEntityLst = weixinExpandconfigService.findByQueryString("FROM WeixinExpandconfigEntity");
//			if (weixinExpandconfigEntityLst.size() != 0) {
//				for (WeixinExpandconfigEntity wec : weixinExpandconfigEntityLst) {
//					boolean findflag = false;// 是否找到关键字信息
//					// 如果已经找到关键字并处理业务，结束循环。
//					if (findflag) {
//						break;// 如果找到结束循环
//					}
//					String[] keys = wec.getKeyword().split(",");
//					for (String k : keys) {
//						if (content.indexOf(k) != -1) {
//							String className = wec.getClassname();
//							KeyServiceI keyService = (KeyServiceI) Class.forName(className).newInstance();
//							respMessage = keyService.excute(content,textMessage, request);
//							findflag = true;// 改变标识，已经找到关键字并处理业务，结束循环。
//							break;// 当前关键字信息处理完毕，结束当前循环
//						}
//					}
//				}
//			}
		}
		return respMessage;
	}
	/**
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2016-3-11 下午3:59:13
	 * @param id
	 * @return
	 */
	private WeixinResponse findByKey(String accoutId,String content)
	{
		List<WeixinResponse> weixinResponses = weixinResponseService.getResponseByAccountId(accoutId);
		for (WeixinResponse weixinResponse : weixinResponses)
		{
			// 如果包含关键字
			String kw = weixinResponse.getKeyWord();
			String[] allkw = kw.split(",");
			for (String k : allkw) {
				if (k.equals(content)) {
					return weixinResponse;
				}
			}
		}
		return null;
	}

}
